﻿<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   
    <div id="toolbar">
        <span id="crud" class="ui-widget-header ui-corner-all">
            <input type="radio" id="actions"/><label for="actions">Actions</label>
            <input type="checkbox" onclick="setSelectTrue();" id="setSelectTrue" /><label for="setSelectTrue">Select</label>
            <button onclick="deleteShape();" id="deleteShape">Delete</button>
            <button onclick="undo();" id="undo">Undo</button>             
            <button onclick="clearAll();" id="clearAll">Clear</button>
            <button onclick="prompSaveCanvas();" id="saveCanvas">Save</button>
        </span>

        <span id="options">    
            <input type="radio" id="shapeOptions"/><label for="shapeOptions">Drawing options</label>
	        <input type="radio" name="options" onclick="setShape('Rectangle');" id="Rectangle"/><label for="Rectangle">Rectangle</label>
	        <input type="radio" name="options" onclick="setShape('Circle');" id="Circle"/><label for="Circle">Circle</label>
	        <input type="radio" name="options" onclick="setShape('Line');" id="Line"/><label for="Line">Line</label>
            <input type="radio" name="options" onclick="setShape('Pen');" id="Pen"/><label for="Pen">Pen</label>
            <input type="radio" name="options" onclick="setImageTrue('Text');" id="textarea"/><label for="textarea">Text</label>
            <input type="radio" name="options" onclick="setImageTrue('MathText');" id="matharea"/><label for="matharea">Math</label>
	        <input type="radio" name="options" onclick="setImageTrue('Leftedge');" id="leftEdge"/><label for="leftEdge">Left edge</label>
            <input type="radio" name="options" onclick="setImageTrue('Rightedge');" id="rightEdge"/><label for="rightEdge">Right edge</label>
            <input type="radio" name="options" onclick="setImageTrue('Node');" id="node"/><label for="node">Node</label>
            <input type="radio" name="options" onclick="setImageTrue('TwoChildren');" id="twoChildren"/><label for="twoChildren">Two Children</label>
            <input type="radio" name="options" onclick="setImageTrue('LeftChild');" id="leftChild"/><label for="leftChild">Left Child</label>
            <input type="radio" name="options" onclick="setImageTrue('RightChild');" id="rightChild"/><label for="rightChild">Right Child</label>

	    </span>
        <div class="clear"></div>
    </div>
    <div id="main">
        <canvas id="theCanvas" height="400" width="915" style="position:absolute;">
	        <p>No support for canvas, sorry</p>
        </canvas>  
        <input id="text" hidden="hidden" type="text" style="position:relative; margin-top: 3px; margin-left: 3px; border: 2px solid orange;"/>
        <div id="math" hidden="hidden" style="position:relative; margin-top: 3px; margin-left: 3px;">
            <span id="mathtext" class="mathquill-editable">f(x)=?</span>
        </div>       
    </div>

    <span id="setPenColor" class="ui-widget-header ui-corner-all">
    <input type="radio" id="penColor"/><label for="penColor">Pen Colors</label>
	    <input type="radio" name="setPenColor" onclick="setColor('Black')" id="setPenBlack"/><label for="setPenBlack">Black</label>
	    <input type="radio" name="setPenColor" onclick="setColor('Red')" id="setPenRed"/><label for="setPenRed">Red</label>
        <input type="radio" name="setPenColor" onclick="setColor('Green')" id="setPenGreen"/><label for="setPenGreen">Green</label>
        <input type="radio" name="setPenColor" onclick="setColor('Blue')" id="setPenBlue"/><label for="setPenBlue">Blue</label>
    </span>

    <span id="setShapeColor" class="ui-widget-header ui-corner-all">
        <input type="radio" id="shapeColor"/><label for="shapeColor">Shape Colors</label>
        <input type="radio" name="setShapeColor" onclick="setShapeColor('None')" id="setShapeNone"/><label for="setShapeNone">None</label>
	    <input type="radio" name="setShapeColor" onclick="setShapeColor('Black')" id="setShapeBlack"/><label for="setShapeBlack">Black</label>
	    <input type="radio" name="setShapeColor" onclick="setShapeColor('Red')" id="setShapeRed"/><label for="setShapeRed">Red</label>
        <input type="radio" name="setShapeColor" onclick="setShapeColor('Green')" id="setShapeGreen"/><label for="setShapeGreen">Green</label>
        <input type="radio" name="setShapeColor" onclick="setShapeColor('Blue')" id="setShapeBlue"/><label for="setShapeBlue">Blue</label>
    </span>
    <div class="clear"></div>

    <p id="message"></p>



    <div id="users-contain" class="ui-widget">
    <% if (Request.IsAuthenticated)
    { %>
	    <h1>Existing Canvas:</h1>
	    <table id="users" class="ui-widget ui-widget-content">
		    <thead>
			    <tr class="ui-widget-header ">
				    <th>Name</th>
				    <th>Date</th>
                    <th></th>
                    <th></th>
			    </tr>
		    </thead>
		    <tbody>
            <% Html.RenderAction("CanvasList", "Home"); %>
		    </tbody>
	    </table>
    <% } %>
    </div>

    <div id="dialog-form" title="Save Canvas">
        <p class="validateTips">If you are not logged in, you will be redirected to the login page. Warning! If you quit the login process the drawing will be lost.</p>
	    <p class="validateTips">Field is required.</p>
	    <form>
	    <fieldset>
		    <label for="name">Name</label>
		    <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
	    </fieldset>
	    </form>
    </div>

<script type="text/javascript">

    $(function () {
        $("#text").hide();
        $("#math").hide();
        $("#setShapeNone").attr('checked', true).button("refresh");
        $("#setPenBlack").attr('checked', true).button("refresh");

        $("#setSelectTrue").button({
            text: false,
            icons: {
                primary: "ui-icon-check"
            }
        });
        $("#undo").button({
            text: false,
            icons: {
                primary: "ui-icon-arrowreturnthick-1-w"
            }
        });
        $("#deleteShape").button({
            text: false,
            disabled: true,
            icons: {
                primary: "ui-icon-trash"
            }
        });
        $("#clearAll").button({
            text: false,
            icons: {
                primary: "ui-icon-close"
            }
        });
        $("#saveCanvas").button({
            text: false,
            icons: {
                primary: "ui-icon-disk"
            }
        });

        $("#crud").buttonset();
        $("#actions").button("disable");
        $("#options").buttonset();
        $("#shapeOptions").button("disable");  
        $("#Rectangle").button({
            text: false,
            icons: {
                primary: "ui-icon-stop"
            }
        });
        $("#Circle").button({
            text: false,
            icons: {
                primary: "ui-icon-radio-on"
            }
        });
        $("#Pen").button({
            text: false,
            icons: {
                primary: "ui-icon-pencil"
            }
        });
        $("#Line").button({
            text: false,
            icons: {
                primary: "ui-icon-minus"
            }
        });
        $("#textarea").button({
            text: false,
            icons: {
                primary: "ui-icon-comment"
            }
        });
        $("#matharea").button({
            text: false,
            icons: {
                primary: "ui-icon-calculator"
            }
        });

        $("#setPenColor").buttonset();

        $("#setPenBlack").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom3',
                secondary: null 
            }
        });
        $("#setPenRed").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom2',
                secondary: null 
            }
        });
        $("#setPenGreen").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom1',
                secondary: null 
            }
        });
        $("#setPenBlue").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom4',
                secondary: null 
            }
        });

        $("#setShapeColor").buttonset();
        $("#penColor").button("disable");
        $("#shapeColor").button("disable");    

        $("#leftEdge").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom6',
                secondary: null
            }
        });
        $("#rightEdge").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom7',
                secondary: null
            }
        });
        $("#node").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom5',
                secondary: null
            }
        });
        $("#twoChildren").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom8',
                secondary: null
            }
        });
        $("#leftChild").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom9',
                secondary: null
            }
        });
        $("#rightChild").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom10',
                secondary: null
            }
        });

        $("#setShapeBlack").button({
            text: false,
            icons: { 
                primary: 'ui-icon-custom3',
                secondary: null 
            }
        });
        $("#setShapeRed").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom2',
                secondary: null 
            }
        });
        $("#setShapeGreen").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom1',
                secondary: null 
            }
        });
        $("#setShapeBlue").button({
            text: false,
            icons: {
                primary: 'ui-icon-custom4',
                secondary: null 
            }
        });
        $(".loadimg").button({
            text: false,
            icons: {
                primary: 'ui-icon-plusthick',
                secondary: null
            }
        });
        $(".deleteimg").button({
            text: false,
            icons: {
                primary: 'ui-icon-closethick',
                secondary: null
            }
        });
        
        // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
        $("#dialog:ui-dialog").dialog("destroy");

        var name = $("#name"),
			email = $("#email"),
			password = $("#password"),
			allFields = $([]).add(name).add(email).add(password),
			tips = $(".validateTips");

        function updateTips(t) {
            tips
				.text(t)
				.addClass("ui-state-highlight");
            setTimeout(function () {
                tips.removeClass("ui-state-highlight", 1500);
            }, 500);
        }

        function checkLength(o, n, min, max) {
            if (o.val().length > max || o.val().length < min) {
                o.addClass("ui-state-error");
                updateTips("Length of " + n + " must be between " +
					min + " and " + max + ".");
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp(o, regexp, n) {
            if (!(regexp.test(o.val()))) {
                o.addClass("ui-state-error");
                updateTips(n);
                return false;
            } else {
                return true;
            }
        }

        $("#dialog-form").dialog({
            autoOpen: false,
            height: 300,
            width: 350,
            modal: true,
            buttons: {
                "Save Canvas": function () {
                    var bValid = true;
                    allFields.removeClass("ui-state-error");

                    bValid = bValid && checkLength(name, "canvas name", 3, 30);

                    bValid = bValid && checkRegexp(name, /^[a-z]([0-9a-z_])+$/i, "Name may consist of a-z, 0-9, underscores, begin with a letter.");
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/

                    if (bValid) {
                        saveCanvas();
                        $(this).dialog("close");
                    }
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            },
            close: function () {
                allFields.val("").removeClass("ui-state-error");
            }
        });

        $("#saveCanvas")
			.button()
			.click(function () {
			    if (shapes.length < 1) {
			        alert("Nothing to save!");
			        return;
			    }
			    $("#dialog-form").dialog("open");
			});
    });


    var canvas = document.getElementById("theCanvas");
    var context = canvas.getContext("2d");
    var mouseIsDown = false;
    var shapes = [];
    var factory;
    var color = "Black";
    var shapeColor = "None";
    var dragging = false;
    var selection = null;
    var selectionIndex = null;
    var select = false;
    var currentcolor;
    var isImageOrText = false;

    function downloadImage() {
        Canvas2Image.saveAsPNG(canvas);
    }

    function deleteCanvas(id) {
        $.post("/Home/DeleteCanvas", { canvasId: id }, function (data) {
            if (data.length > 0) {
                $('#users tbody').empty();
                for (var i = 0; i < data.length; i++) {
                    $("#users tbody").append("<tr>" +
                        "<td>" + data[i].Name + "</td>" +
                        "<td>" + data[i].Date.toString() + "</td>" +
                        "<td><button onclick='loadCanvas(" + data[i].ID + ");' class='loadimg'>load</button></td>" +
                        "<td><button onclick='deleteCanvas(" + data[i].ID + ");' class='deleteimg'>Delete</button></td>" +
                    "</tr>");
                    //$('.shapeList').append('<li><a onclick="loadCanvas(' + data[i].ID + ');">' + data[i].Name + '</a></li>');
                }
                $(".loadimg").button({
                    text: false,
                    icons: {
                        primary: 'ui-icon-plusthick',
                        secondary: null
                    }
                });
                $(".deleteimg").button({
                    text: false,
                    icons: {
                        primary: 'ui-icon-closethick',
                        secondary: null
                    }
                });
            }
            else {
                $('#users tbody').empty(); 
            }

        });
        return false;
    }

    function saveCanvas() {
        var canvas = JSON.stringify(shapes, null, 2);
        var name = $("#name").val();
        $.post("/Home/SaveCanvas", { TheCanvas: canvas, TheCanvasName: name }, function (data) {
            if (data.length > 0) {
                $('#users tbody').empty();
                for (var i = 0; i < data.length; i++) {
                    $("#users tbody").append("<tr>" +
                        "<td>" + data[i].Name + "</td>" +
                        "<td>" + data[i].Date.toString() + "</td>" +
                        "<td><button onclick='loadCanvas(" + data[i].ID + ");' class='loadimg'>load</button></td>" +
                        "<td><button onclick='deleteCanvas(" + data[i].ID + ");' class='deleteimg'>Delete</button></td>" +
                    "</tr>");
                }
                $(".loadimg").button({
                    text: false,
                    icons: {
                        primary: 'ui-icon-plusthick',
                        secondary: null
                    }
                });
                $(".deleteimg").button({
                    text: false,
                    icons: {
                        primary: 'ui-icon-closethick',
                        secondary: null
                    }
                });
            }
            else {
                document.location.href = 'http://localhost:51267/Account/LogOn';
//                    alert('Save unsuccesfull! You need to log in for saving...');
            }
        });
        return false;
    }

    function loadCanvas(id) {
        $.ajax(
        {
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "/Home/GetShapes/",
            data: { canvasId: id },
            dataType: "json",
            success: function (data) {
                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var your_object = JSON.parse(data[i].TheShapes);
                        for (var j = 0; j < your_object.length; j++) {
                            var obj = your_object[j];
                            if (obj.name == "Rectangle") {
                                var rec = createRect(obj);
                                shapes.push(rec);
                            }
                            if (obj.name == "Circle") {
                                var cir = createCirc(obj);
                                shapes.push(cir);
                            }
                            if (obj.name == "Line") {
                                var line = createLine(obj);
                                shapes.push(line);
                            }
                            if (obj.name == "Pen") {
                                var pen = createPen(obj);
                                shapes.push(pen);
                            }
                            if (obj.name == "Text") {
                                var text = createText(obj);
                                shapes.push(text);
                            }
                            if (obj.name == "Leftedge") {
                                var leftedge = createLeftedge(obj);
                                shapes.push(leftedge);
                            }
                            if (obj.name == "Rightedge") {
                                var rightedge = createRightedge(obj);
                                shapes.push(rightedge);
                            }
                            if (obj.name == "TwoChildren") {
                                var twochildren = createTwoChildren(obj);
                                shapes.push(twochildren);
                            }

                            if (obj.name == "LeftChild") {
                                var leftchild = createLeftChild(obj);
                                shapes.push(leftchild);
                            }
                            if (obj.name == "RightChild") {
                                var rightchild = createRightChild(obj);
                                shapes.push(rightchild);
                            }
                            if (obj.name == "Node") {
                                var node = createNode(obj);
                                shapes.push(node);
                            }
                            if (obj.name == "Math") {
                                var math = createMathText(obj);
                                shapes.push(math);
                            }
                        }
                    }
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    reDraw();
                }
            },
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);
            }
        });        
    }

    function setSelectTrue() {
        $("#text").hide();
        select = true;
        isImageOrText = false;
        $("#Rectangle").attr('checked', false).button("refresh");
        $("#Circle").attr('checked', false).button("refresh");
        $("#Line").attr('checked', false).button("refresh");
        $("#Pen").attr('checked', false).button("refresh");
        $("#textarea").attr('checked', false).button("refresh");
        $("#deleteShape").button("enable");
    }

    function clearAll() {
        context.clearRect(0, 0, canvas.width, canvas.height);
        shapes = [];
    }

    function deleteShape() {
        if (selection != null && select == true && selectionIndex != null) {
            shapes.splice(selectionIndex, 1);
            selectionIndex = null;
            context.clearRect(0, 0, canvas.width, canvas.height);
            reDraw();
        }
    }

    function undo() {
        shapes.pop();
        context.clearRect(0, 0, canvas.width, canvas.height);
        reDraw();
    }

    function setColor(selectedColor) {
        color = selectedColor;
        $("#deleteShape").button("disable");
        select = false;
        $("#setSelectTrue").attr('checked', false).button("refresh");
    }

    function setShapeColor(selectedShapeColor) {
        shapeColor = selectedShapeColor;
        $("#deleteShape").button("disable");
        select = false;
        $("#setSelectTrue").attr('checked', false).button("refresh");
    }

    function setImageTrue(shapeName) {
        $("#text").hide();
        $("#math").hide();
        if (shapeName == "Text") {
            $("#text").show();
        }
        if (shapeName == "MathText") {
            $("#math").show();
        }
            
        isImageOrText = true;
        select = false;
        $("#deleteShape").button("disable");
        $("#setSelectTrue").attr('checked', false).button("refresh");
        factory = function (x, y) {
            return eval("new " + shapeName + "(" + x + "," + y + ");");
        }
    }

    function setShape(shapeName) {
        $("#text").hide();
        $("#math").hide();
        select = false;
        $("#deleteShape").button("disable");
        isImageOrText = false;
        $("#setSelectTrue").attr('checked', false).button("refresh");
        factory = function (x, y) {
            return eval("new " + shapeName + "(" + x + "," + y + ");");
        }
    }

    function MathText(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;
        this.mathLocation = $("#mathtext").mathquill('latex');
        this.img = new Image();
        this.img.src = "http://latex.codecogs.com/gif.latex?" + this.mathLocation;
        this.name = "Math";

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0;
    }

    function createMathText(obj) {
        var result = new MathText(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.mathLocation = obj.mathLocation;
        result.img = new Image();
        result.img.src = "http://latex.codecogs.com/gif.latex?" + obj.mathLocation;
        result.name = obj.name;
        result.startdragoffx = obj.startdragoffx;
        result.startdragoffy = obj.startdragoffy;
        result.enddragoffx = obj.enddragoffx;
        result.enddragoffy = obj.enddragoffy;
        return result;
    }

    MathText.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    MathText.prototype.setMove = function (x, y) {
        this.endx = x - this.startdragoffx;
        this.endy = y - this.startdragoffy;
        this.x = this.endx;
        this.y = this.endy;
    }

    MathText.prototype.contains = function (x, y) {
        var height = this.img.height;
        var width = this.img.width;
        if (x >= this.endx && x <= (this.endx + width) && y >= this.endy && y <= (this.endy + height)) {
            return true;
        }
        return false;
    }

    MathText.prototype.draw = function () {
        context.drawImage(this.img, this.endx, this.endy);
    }

    function Text(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0;

        this.color = color;
        this.text = $("#text").val();    
        this.name = "Text";
        
    }

    function createText(obj) {
        var result = new Text(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.text = obj.text;
        result.name = obj.name;
        return result;
    }

    Text.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Text.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
        this.endx = x + this.enddragoffx;
        this.endy = y + this.enddragoffy;
    }

    Text.prototype.contains = function (x, y) {
        var length = this.text.length;
        var beginx = this.x - (10 * (length / 2));
        var endx = this.x + (10 * (length / 2));
        var uppery = this.y - 9;
        var lowery = this.y + 9;

        if (x >= beginx && x <= endx && y >= uppery && y <= lowery) {

            return true;
        }
        return false;
    }

    Text.prototype.draw = function () {
        context.fillStyle = this.color;
        context.lineWidth = 1;
        context.font = "18px sans-serif";
        context.textBaseline = "middle";
        context.textAlign = "center";
        context.fillText(this.text, this.endx, this.endy);
    }

    function Rectangle(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;
        this.color = color;
        this.scolor = shapeColor;
        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0;
        this.name = "Rectangle";
    }

    function createRect(obj)
    {
        var result = new Rectangle(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.scolor = obj.scolor;
        result.startdragoffx = obj.startdragoffx;
        result.startdragoffy = obj.startdragoffy;
        result.enddragoffx = obj.enddragoffx;
        result.enddragoffy = obj.enddragoffy;
        result.name = obj.name;
        return result;
    }

    Rectangle.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Rectangle.prototype.draw = function () {
        context.strokeStyle = this.color; // line color
        context.fillStyle = this.scolor;
        var beginxmin = Math.min(this.x, this.endx);
        var endxmax = Math.max(this.x, this.endx);
        var beginymin = Math.min(this.y, this.endy);
        var endymax = Math.max(this.y, this.endy);
        context.strokeRect(beginxmin, beginymin, Math.abs(endxmax - beginxmin), Math.abs(endymax - beginymin));
        if (this.scolor != "None") {
            context.fillRect(beginxmin, beginymin, Math.abs(endxmax - beginxmin), Math.abs(endymax - beginymin));
        }
    }

    Rectangle.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
        this.endx = x + this.enddragoffx;
        this.endy = y + this.enddragoffy;
    }

    Rectangle.prototype.contains = function (x, y) {
        
        var beginxmin = Math.min(this.x, this.endx);
        var endxmax = Math.max(this.x, this.endx);
        var beginymin = Math.min(this.y, this.endy);
        var endymax = Math.max(this.y, this.endy);

        if (x >= beginxmin && x <= (beginxmin + Math.abs(endxmax - beginxmin)) &&
            y >= beginymin && y <= (beginymin + Math.abs(endymax - beginymin))) {
            return true;
        }
        return false;
    }

    function FindShape(x, y) {
        for (var i = 0; i < shapes.length; i++) {
            if (shapes[i].contains(x, y) == true) {
                selectionIndex = i;
                return shapes[i];
            }
        }
        return null;
    }

    function Circle(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;
        this.color = color;
        this.scolor = shapeColor;
        
        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0;
        this.name = "Circle";
    }

    function createCirc(obj) {
        var result = new Circle(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.scolor = obj.scolor;
        result.name = obj.name;
        result.startdragoffx = obj.startdragoffx;
        result.startdragoffy = obj.startdragoffy;
        result.enddragoffx = obj.enddragoffx;
        result.enddragoffy = obj.enddragoffy;
        return result;
    }

    Circle.prototype.contains = function (x, y) {
        var beginxmin = Math.min(this.x, this.endx);
        var endxmax = Math.max(this.x, this.endx);
        var beginymin = Math.min(this.y, this.endy);
        var endymax = Math.max(this.y, this.endy);
        
        var radius = (Math.abs(endxmax - beginxmin) + Math.abs(endymax - beginymin)) / 2;
        var left_x = ((beginxmin + endxmax) / 2) - radius;
        var right_x = ((beginxmin + endxmax) / 2) + radius;
        var upper_y = ((beginymin + endymax) / 2) - radius;
        var lower_y = ((beginymin + endymax) / 2) + radius;

        if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
            return true;
        }
        return false;
    }

    Circle.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Circle.prototype.draw = function () {
        context.strokeStyle = this.color; // line color
        context.fillStyle = this.scolor;
        var beginxmin = Math.min(this.x, this.endx);
        var endxmax = Math.max(this.x, this.endx);
        var beginymin = Math.min(this.y, this.endy);
        var endymax = Math.max(this.y, this.endy);
        context.beginPath();
        context.arc((beginxmin + endxmax) / 2, (beginymin + endymax) / 2, (Math.abs(endxmax - beginxmin) + Math.abs(endymax - beginymin)) / 2, 0, Math.PI * 2, true);
        context.closePath();
        if (this.scolor != "None") {
            context.fill();
        }
        context.stroke();
    }

    Circle.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
        this.endx = x + this.enddragoffx;
        this.endy = y + this.enddragoffy;
    }

    function Pen(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.color = color;
        this.points = [];
        this.firstPoint = { "x": this.x, "y": this.y };
        this.nextPoint = { "x": this.x, "y": this.y };
        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0; // ÞETTA ER Í RAUN ÓÞARFI
        this.enddragoffy = 0; //ÞETTA LÍKA
        this.points.push(this.firstPoint);
        this.name = "Pen";
    }

    function createPen(obj) {
        var result = new Pen(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.color = obj.color;
        result.points = obj.points;
        result.firstPoint = obj.firstPoint;
        result.nextPoint = obj.nextPoint;

        result.startdragoffx = obj.startdragoffx;
        result.startdragoffy = obj.startdragoffy;
        result.enddragoffx = obj.enddragoffx; // ÞETTA ER Í RAUN ÓÞARFI
        result.enddragoffy = obj.enddragoffy; //ÞETTA LÍKA

        result.name = obj.name;
        return result;
    }

    Pen.prototype.setMove = function (x, y) {
        //TODO fix this bug 
//        var variablex = this.firstPoint.x;
//        var variabley = this.firstPoint.y;
//     
//        this.firstPoint.x = x + this.startdragoffx;
//        this.firstPoint.y = y + this.startdragoffy;

//        var changex = variablex - this.firstPoint.x;
//        var changey = variabley - this.firstPoint.y;

//        for (var i = 0; i < this.points.length; i++) {
//            this.points[i].x -= changex;
//            this.points[i].y -= changey;
//        }

    }

    Pen.prototype.contains = function (x, y) {

        for (var i = 0; i < this.points.length; i++) {

            var left_x = this.points[i].x - 5;
            var right_x = this.points[i].x + 5;
            var upper_y = this.points[i].y - 5;
            var lower_y = this.points[i].y + 5;
            
            if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
                return true;
            }
        }
        return false;
    }

    Pen.prototype.setEnd = function (x, y) {
        this.nextPoint = { "x": x, "y": y };
        this.points.push(this.nextPoint);
    }

    Pen.prototype.draw = function () {
        context.strokeStyle = this.color; // line color
        context.beginPath();
        for (var i = 0; i < this.points.length - 1; i++) {
            context.moveTo(this.points[i].x, this.points[i].y);
            context.lineTo(this.points[i + 1].x, this.points[i + 1].y);
        }
        context.stroke();
    }

    function Line(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;
        this.color = color;
        this.name = "Line";

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0; 
        this.enddragoffy = 0; 
    
    }

    function createLine(obj) {
        var result = new Line(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    Line.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Line.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
        this.endx = x + this.enddragoffx;
        this.endy = y + this.enddragoffy;    
    }

    Line.prototype.contains = function (x, y) {
      
        var slope = (this.endy - this.y) / (this.endx - this.x);

        var line = (((x * slope) - (this.x * slope)) + this.y)
        if (y >= (line - 10) && y <= (line + 10)) {
            return true;
        }
        return false;
    }

    Line.prototype.draw = function () {
        context.beginPath();
        context.strokeStyle = this.color;
        context.moveTo(this.x, this.y);
        context.lineTo(this.endx, this.endy);
        context.stroke();
    }

    function Leftedge(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "Leftedge";
    }

    function createLeftedge(obj) {
        var result = new Leftedge(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    Leftedge.prototype.draw = function () {
        context.strokeStyle = this.color; //line color
        context.beginPath();
        context.moveTo(this.x, this.y);
        context.lineTo((this.x - 10), (this.y + 30));
        context.stroke();
    }

    Leftedge.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Leftedge.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    Leftedge.prototype.contains = function (x, y) {

        if (x >= (this.x-10) && x <= this.x && y >= this.y && y <= (this.y + 30)) {
            return true;
        }
        return false;
    }

    function Rightedge(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;
        this.endx = (x === undefined) ? 0 : x;
        this.endy = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "Rightedge";
    }

    function createRightedge(obj) {
        var result = new Rightedge(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.endx = obj.endx;
        result.endy = obj.endy;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    Rightedge.prototype.draw = function () {
        context.strokeStyle = this.color; //line color
        context.beginPath();
        context.moveTo(this.x, this.y);
        context.lineTo((this.x + 10), (this.y + 30));
        context.stroke();
    }

    Rightedge.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Rightedge.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    Rightedge.prototype.contains = function (x, y) {
     
        if (x >= this.x && x <= (this.x + 10) && y >= this.y && y <= (this.y + 30)) {
            return true;
        }
        return false; 
    }

    function TwoChildren(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "TwoChildren";
    }

    function createTwoChildren(obj) {
        var result = new TwoChildren(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    TwoChildren.prototype.draw = function () {
        this.leftbegx = (this.x - 5);
        this.begy = (this.y + 15);
        this.rightbegx = (this.x + 5);
        context.strokeStyle = this.color; // line color
        context.beginPath();
        context.arc(this.x, this.y, 15, 0, Math.PI * 2, true);
        context.moveTo(this.leftbegx, this.begy);
        context.lineTo((this.leftbegx - 10), (this.begy + 30));
        context.moveTo(this.rightbegx, this.begy);
        context.lineTo((this.rightbegx + 10), (this.begy + 30));
        context.closePath();
        context.stroke();
    }

    TwoChildren.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    TwoChildren.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    TwoChildren.prototype.contains = function (x, y) {
        var left_x = this.x - 15;
        var right_x = this.x + 15;
        var upper_y = this.y - 15;
        var lower_y = this.y + 15;

        if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
            return true;
        }
        return false;
    }

    function LeftChild(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "LeftChild";
    }

    function createLeftChild(obj) {
        var result = new LeftChild(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    LeftChild.prototype.draw = function () {
        this.leftbegx = (this.x - 5);
        this.begy = (this.y + 15);
        context.strokeStyle = this.color; // line color
        context.beginPath();
        context.arc(this.x, this.y, 15, 0, Math.PI * 2, true);
        context.moveTo(this.leftbegx, this.begy);
        context.lineTo((this.leftbegx - 10), (this.begy + 30));
        context.closePath();
        context.stroke();
    }

    LeftChild.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    LeftChild.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    LeftChild.prototype.contains = function (x, y) {
        var left_x = this.x - 15;
        var right_x = this.x + 15;
        var upper_y = this.y - 15;
        var lower_y = this.y + 15;

        if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
            return true;
        }
        return false;
    }

    function RightChild(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "RightChild";
    }

    function createRightChild(obj) {
        var result = new RightChild(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    RightChild.prototype.draw = function () {
        this.rightbegx = (this.x + 5);
        this.begy = (this.y + 15);
        context.strokeStyle = this.color; // line color
        context.beginPath();
        context.arc(this.x, this.y, 15, 0, Math.PI * 2, true);
        context.moveTo(this.rightbegx, this.begy);
        context.lineTo((this.rightbegx + 10), (this.begy + 30));
        context.closePath();
        context.stroke();
    }

    RightChild.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    RightChild.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    RightChild.prototype.contains = function (x, y) {
        var left_x = this.x - 15;
        var right_x = this.x + 15;
        var upper_y = this.y - 15;
        var lower_y = this.y + 15;

        if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
            return true;
        }
        return false;
    }

    function Node(x, y) {
        this.x = (x === undefined) ? 0 : x;
        this.y = (y === undefined) ? 0 : y;

        this.startdragoffx = 0;
        this.startdragoffy = 0;
        this.enddragoffx = 0;
        this.enddragoffy = 0; 

        this.color = color;
        this.name = "Node";
    }

    function createNode(obj) {
        var result = new Node(obj.x, obj.y);
        result.x = obj.x;
        result.y = obj.y;
        result.color = obj.color;
        result.name = obj.name;
        return result;
    }

    Node.prototype.draw = function () {
        context.strokeStyle = this.color; // line color
        context.beginPath();
        context.arc(this.x, this.y, 15, 0, Math.PI * 2, true);
        context.closePath();
        context.stroke();
    }

    Node.prototype.setEnd = function (x, y) {
        this.endx = x;
        this.endy = y;
    }

    Node.prototype.setMove = function (x, y) {
        this.x = x - this.startdragoffx;
        this.y = y - this.startdragoffy;
    }

    Node.prototype.contains = function (x, y) {
        var left_x = this.x - 15;
        var right_x = this.x + 15;
        var upper_y = this.y - 15;
        var lower_y = this.y + 15;

        if (x >= left_x && x <= right_x && y >= upper_y && y <= lower_y) {
            return true;
        }
        return false;
    }

    function reDraw() {
        for (var i = 0; i < shapes.length; i++) {
            var shape = shapes[i];
            shape.draw();
        }
    }

    $(document).ready(function () {

        $("#theCanvas").mousedown(function (e) {
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            if (select == true) {
                var mySel = FindShape(x, y);
                if (mySel != null) {
                    currentcolor = mySel.color;
                    mySel.color = "Purple";
                    mySel.startdragoffx = x - mySel.x;
                    mySel.startdragoffy = y - mySel.y;
                    mySel.enddragoffx = mySel.endx - x;
                    mySel.enddragoffy = mySel.endy - y;
                    selection = mySel;
                    dragging = true;
                    return;
                }
                if (selection != null) {
                    selection.color = currentcolor;
                    selection = null;
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    reDraw();
                }
            }
            else if (isImageOrText != true) {
                var shape = factory(x, y);
                shapes.push(shape);
                mouseIsDown = true;
            }
        });

        $("#theCanvas").mouseup(function (e) {
            mouseIsDown = false;
            if (dragging == true) { 
                dragging = false;
                selection.color = currentcolor;
            }
            
        });

        $("#theCanvas").mousemove(function (e) {
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;

            if (mouseIsDown == true) {
                var lastShape = shapes[shapes.length - 1];

                if (lastShape != undefined) {
                    lastShape.setEnd(x, y);
                }

                context.clearRect(0, 0, canvas.width, canvas.height);
                reDraw();
            }
            else if (dragging == true) {
                if (selection != undefined) {
                    selection.setMove(x, y);
                }
                context.clearRect(0, 0, canvas.width, canvas.height);
                reDraw();
            }
        });

        $("#theCanvas").click(function (e) {
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            if (isImageOrText == true) {
                var shape = factory(x, y);
                shapes.push(shape);
                context.clearRect(0, 0, canvas.width, canvas.height);
                reDraw();
            }
        });
    });
</script>
</asp:Content>
